import 'package:dio/dio.dart';
import 'package:f_enjoy_plus/components/Header.dart';
import 'package:f_enjoy_plus/core/constants/app_colors.dart';
import 'package:f_enjoy_plus/utils/http.dart';
import 'package:f_enjoy_plus/utils/loadImage.dart';
import 'package:f_enjoy_plus/utils/toast.dart';
import 'package:flutter/material.dart';
import 'dart:math';
import 'package:f_enjoy_plus/utils/loading.dart';
import 'package:get/state_manager.dart';

class AddHouse extends StatefulWidget {
  final Map routerParams;
  const AddHouse({super.key, required this.routerParams});

  @override
  State<AddHouse> createState() => _AddHouseState();
}

class _AddHouseState extends State<AddHouse> {
  String id = '';
  bool showPicker = false;

  // 文本控制器
  late TextEditingController _nameController;
  late TextEditingController _mobileController;

  // 随机生成楼栋数据
  List<String> buildings = [];
  List<String> units = [];
  List<String> rooms = [];

  final Map _formData = {
    'point': '古北壹号', // 小区信息
    'building': '1', // 楼栋信息
    'unit': '1单元', // 新增单元字段
    'room': '101', // 房间号
    'name': '小猪zang', // 业主姓名
    'gender': 1, // 业主性别0女1男
    'mobile': '13412341234', // 业主电话
    'idcardFrontUrl':
        'http://yjy-teach-oss.oss-cn-beijing.aliyuncs.com/livimini/production/20250626/7171766944391168.jpg', // 身份证正面
    'idcardBackUrl':
        'http://yjy-teach-oss.oss-cn-beijing.aliyuncs.com/livimini/production/20250626/7171766990798848.jpg', // 身份证背面
  };

  @override
  void initState() {
    super.initState();

    // 初始化控制器
    _nameController = TextEditingController(text: _formData['name']);
    _mobileController = TextEditingController(text: _formData['mobile']);

    // 生成随机楼栋数据
    generateRandomData();

    // 判断是否是编辑模式
    bool isEditMode =
        widget.routerParams.containsKey('id') &&
        widget.routerParams['id'] != null &&
        widget.routerParams['id'].isNotEmpty;

    if (isEditMode) {
      // 编辑模式：处理数据回显
      _formData['id'] = widget.routerParams['id'];
      print('编辑模式 ID: ${widget.routerParams['id']}');
      parseRoomData();
      getHouseInfo();
    } else if (widget.routerParams.containsKey('name') &&
        widget.routerParams['name'] != null) {
      // 新增模式且有小区名称：自动弹出级联选择器
      print('新增模式，小区名称: ${widget.routerParams['name']}');
      Future.delayed(Duration.zero, () {
        showCascadePicker();
      });
    }
  }

  getHouseInfo() async {
    try {
      final res = await http.get('/room/${widget.routerParams['id']}');
      setState(() {
        _formData['building'] = res['building'];
        _formData['unit'] = res['unit'];
        _formData['room'] = res['room'];
        _formData['point'] = res['point'];
        _formData['name'] = res['name'];
        _formData['gender'] = res['gender'];
        _formData['mobile'] = res['mobile'];
        _formData['idcardFrontUrl'] = res['idcardFrontUrl'];
        _formData['idcardBackUrl'] = res['idcardBackUrl'];

        // 更新控制器文本
        _nameController.text = res['name'] ?? '';
        _mobileController.text = res['mobile'] ?? '';
      });
    } catch (e) {
      print(e);
    }
  }

  void generateRandomData() {
    // 随机生成3-8栋
    int buildingCount = Random().nextInt(6) + 3;
    buildings = List.generate(buildingCount, (index) => '${index + 1}栋');

    // 随机生成3-6单元
    int unitCount = Random().nextInt(3) + 3;
    units = List.generate(unitCount, (index) => '${index + 1}单元');

    // 生成门牌号 (101-699)
    List<String> roomList = [];
    for (int floor = 1; floor <= 6; floor++) {
      for (int room = 1; room <= 9; room++) {
        roomList.add('${floor}0${room}');
      }
    }
    rooms = roomList;
  }

  // 解析room数据，分离单元和房间号
  void parseRoomData() {
    // 假设room的格式是"单元-房间号"，例如"1单元-101"
    if (_formData['room'] != null) {
      String roomValue = _formData['room'] as String;
      if (roomValue.contains('-')) {
        List<String> parts = roomValue.split('-');
        if (parts.length == 2) {
          setState(() {
            _formData['unit'] = parts[0];
            _formData['room'] = parts[1];
          });
        }
      }
    }
  }

  void showCascadePicker() {
    // 创建临时变量存储选择的值，使用现有值进行初始化
    String tempBuilding = _formData['building'] ?? '';
    String tempUnit = _formData['unit'] ?? '';
    String tempRoom = _formData['room'] ?? '';

    showModalBottomSheet(
      context: context,
      isScrollControlled: true, // 允许内容滚动
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(10)),
      ),
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setModalState) {
            return SizedBox(
              height: 300,
              child: Column(
                children: [
                  Container(
                    padding: EdgeInsets.symmetric(horizontal: 16, vertical: 10),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        TextButton(
                          onPressed: () {
                            Navigator.pop(context);
                          },
                          child: Text('取消'),
                        ),
                        Text(widget.routerParams['name'] ?? ''),
                        TextButton(
                          onPressed: () {
                            // 点击确定时更新实际数据
                            setState(() {
                              _formData['building'] = tempBuilding;
                              _formData['unit'] = tempUnit; // 保存单元到单独的字段
                              _formData['room'] = tempRoom; // 房间号单独保存
                              _formData['point'] = widget.routerParams['name'];
                            });
                            Navigator.pop(context);
                          },
                          child: Text('确定'),
                        ),
                      ],
                    ),
                  ),
                  Divider(height: 1),
                  Expanded(
                    child: Row(
                      children: [
                        // 楼栋选择
                        Expanded(
                          child: ListView.builder(
                            itemCount: buildings.length,
                            itemBuilder: (context, index) {
                              return ListTile(
                                title: Text(buildings[index]),
                                selected: tempBuilding == buildings[index],
                                onTap: () {
                                  // 只在模态内更新临时变量
                                  setModalState(() {
                                    tempBuilding = buildings[index];
                                  });
                                },
                              );
                            },
                          ),
                        ),
                        // 单元选择
                        Expanded(
                          child: ListView.builder(
                            itemCount: units.length,
                            itemBuilder: (context, index) {
                              return ListTile(
                                title: Text(units[index]),
                                selected: tempUnit == units[index],
                                onTap: () {
                                  // 只在模态内更新临时变量
                                  setModalState(() {
                                    tempUnit = units[index];
                                  });
                                },
                              );
                            },
                          ),
                        ),
                        // 门牌号选择
                        Expanded(
                          child: ListView.builder(
                            itemCount: rooms.length,
                            itemBuilder: (context, index) {
                              return ListTile(
                                title: Text(rooms[index]),
                                selected: tempRoom == rooms[index],
                                onTap: () {
                                  // 只在模态内更新临时变量
                                  setModalState(() {
                                    tempRoom = rooms[index];
                                  });
                                },
                              );
                            },
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            );
          },
        );
      },
    );
  }

  void showImagePickerBottomSheet(String title, String type) {
    LoadImageUtils.showImagePickerBottomSheet(
      context: context,
      title: title,
      onImageSelected: (path, dialogContext) async {
        await uploadImage(path, type);
        // 上传完成后关闭底部弹窗
        Navigator.pop(dialogContext);
      },
    );
  }

  uploadImage(String path, String type) async {
    // 显示全局loading
    LoadingUtils.show(message: '上传中...');

    try {
      FormData fd = FormData.fromMap({
        'file': MultipartFile.fromFileSync(path, filename: 'idcard.jpg'),
      });
      final res = await http.post('/upload', fd);
      setState(() {
        if (type == 'idcardFront') {
          _formData['idcardFrontUrl'] = res['url'] ?? '';
        } else {
          _formData['idcardBackUrl'] = res['url'] ?? '';
        }
      });
      print(res);
    } catch (e) {
      print(e);
    } finally {
      // 隐藏全局loading
      LoadingUtils.hide();
    }
  }

  validate() {
    if (_formData['name'] == null || _formData['name'].isEmpty) {
      ToastUtils.error('请输入业主姓名');
      return false;
    }
    if (_formData['gender'] == null) {
      ToastUtils.error('请选择业主性别');
      return false;
    }
    if (_formData['mobile'] == null ||
        _formData['mobile'].isEmpty ||
        _formData['mobile'].length != 11) {
      ToastUtils.error('请输入正确的联系电话');
      return false;
    }
    if (_formData['idcardFrontUrl'] == null ||
        _formData['idcardFrontUrl'].isEmpty) {
      ToastUtils.error('请上传人像面照片');
      return false;
    }
    if (_formData['idcardBackUrl'] == null ||
        _formData['idcardBackUrl'].isEmpty) {
      ToastUtils.error('请上传国徽面照片');
      return false;
    }
    return true;
  }

  submit() async {
    try {
      if (!validate()) return;

      // 创建一个新的Map用于提交，避免修改原始_formData
      Map<String, dynamic> submitData = Map.from(_formData);

      // 合并单元和房间号为提交格式
      if (submitData['unit'] != null &&
          submitData['unit'].isNotEmpty &&
          submitData['room'] != null &&
          submitData['room'].isNotEmpty) {
        submitData['room'] = "${submitData['unit']}-${submitData['room']}";
      }

      // 无论如何都移除unit字段，因为API不允许这个字段
      submitData.remove('unit');

      // 打印提交数据，确认unit已被移除
      print("提交数据: $submitData");

      final res = await http.post('/room', submitData);
      print('响应数据: $res');
      ToastUtils.success('提交成功');
      Navigator.popUntil(context, (route) => route.isFirst);
    } catch (e) {
      print('错误: $e');
      ToastUtils.error('提交失败: ${e.toString()}');
    } finally {
      LoadingUtils.hide();
    }
  }

  @override
  void dispose() {
    // 释放控制器资源
    _nameController.dispose();
    _mobileController.dispose();
    super.dispose();
  }

  // 判断是否是编辑模式
  bool get isEditMode {
    return widget.routerParams.containsKey('id') &&
        widget.routerParams['id'] != null &&
        widget.routerParams['id'].isNotEmpty;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: Header(title: isEditMode ? '编辑房源' : '添加房源'),
      body: Column(
        children: [
          Expanded(
            child: ListView(
              padding: EdgeInsets.symmetric(vertical: 16),
              children: [
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Padding(
                      padding: EdgeInsets.all(16),
                      child: Text(
                        '房屋信息',
                        style: TextStyle(
                          fontSize: 12,
                          color: AppColors.textSecondary,
                        ),
                      ),
                    ),
                    GestureDetector(
                      onTap: () {
                        // 只有在非编辑模式下才能点击
                        if (!isEditMode) {
                          showCascadePicker();
                        }
                      },
                      child: Container(
                        padding: EdgeInsets.all(16),
                        color: AppColors.white,
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              '${_formData['point'] ?? ''}-${_formData['building'] ?? ''}-${_formData['unit'] ?? ''}-${_formData['room'] ?? ''}',
                            ),
                            // 只有在非编辑模式下才显示箭头图标
                            Visibility(
                              visible: !isEditMode,
                              child: Icon(
                                Icons.arrow_forward_ios,
                                color: AppColors.textSecondary,
                                size: 16,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.all(16),
                      child: Text(
                        '业主信息',
                        style: TextStyle(
                          fontSize: 12,
                          color: AppColors.textSecondary,
                        ),
                      ),
                    ),
                    Container(
                      padding: EdgeInsets.all(16),
                      color: AppColors.white,
                      child: Row(
                        children: [
                          SizedBox(width: 100, child: Text('姓名')),
                          Expanded(
                            child: TextField(
                              controller: _nameController,
                              decoration: InputDecoration(
                                hintText: '请输入业主姓名',
                                hintStyle: TextStyle(
                                  color: AppColors.textSecondary,
                                  fontSize: 14,
                                ),
                                border: InputBorder.none,
                              ),
                              onChanged: (value) {
                                _formData['name'] = value.toString();
                              },
                            ),
                          ),
                        ],
                      ),
                    ),
                    Container(
                      padding: EdgeInsets.all(16),
                      color: AppColors.white,
                      child: Row(
                        children: [
                          SizedBox(width: 100, child: Text('性别')),
                          Row(
                            children: [
                              Radio(
                                value: 1,
                                groupValue: _formData['gender'],
                                onChanged: (value) {
                                  setState(() {
                                    _formData['gender'] = value;
                                  });
                                },
                              ),
                              Text('男'),
                              SizedBox(width: 20),
                              Radio(
                                value: 0,
                                groupValue: _formData['gender'],
                                onChanged: (value) {
                                  setState(() {
                                    _formData['gender'] = value;
                                  });
                                },
                              ),
                              Text('女'),
                            ],
                          ),
                        ],
                      ),
                    ),
                    Container(
                      padding: EdgeInsets.all(16),
                      color: AppColors.white,
                      child: Row(
                        children: [
                          SizedBox(width: 100, child: Text('联系电话')),
                          Expanded(
                            child: TextField(
                              keyboardType: TextInputType.phone,
                              maxLength: 11,
                              controller: _mobileController,
                              decoration: InputDecoration(
                                hintText: '请输入联系电话',
                                hintStyle: TextStyle(
                                  color: AppColors.textSecondary,
                                  fontSize: 14,
                                ),
                                border: InputBorder.none,
                              ),
                              onChanged: (value) {
                                _formData['mobile'] = value.toString();
                              },
                            ),
                          ),
                        ],
                      ),
                    ),
                    SizedBox(height: 16),
                    Container(
                      padding: EdgeInsets.all(16),
                      color: AppColors.white,
                      width: double.infinity,
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text('本人身份证照片'),
                          SizedBox(height: 8),
                          Text(
                            '请拍摄证件原件，并使照片中证件边缘完整，文字清晰，光线均匀。',
                            style: TextStyle(
                              fontSize: 12,
                              color: AppColors.textSecondary,
                            ),
                          ),
                        ],
                      ),
                    ),
                    GestureDetector(
                      onTap: () {
                        showImagePickerBottomSheet('上传人像面照片', 'idcardFront');
                      },
                      child: Container(
                        padding: EdgeInsets.all(16),
                        margin: EdgeInsets.all(16),
                        width: double.infinity,
                        decoration: BoxDecoration(
                          color: AppColors.white,
                          borderRadius: BorderRadius.circular(8),
                        ),
                        child: AspectRatio(
                          aspectRatio: 16 / 9,
                          child:
                              _formData['idcardFrontUrl'] != null &&
                                      _formData['idcardFrontUrl'].isNotEmpty
                                  ? Image.network(
                                    _formData['idcardFrontUrl'],
                                    fit: BoxFit.cover,
                                  )
                                  : Column(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      Icon(
                                        Icons.add_a_photo_outlined,
                                        size: 24,
                                        color: AppColors.textSecondary,
                                      ),
                                      SizedBox(height: 8),
                                      Text('上传人像面照片'),
                                    ],
                                  ),
                        ),
                      ),
                    ),
                    GestureDetector(
                      onTap: () {
                        showImagePickerBottomSheet('上传国徽面照片', 'idcardBack');
                      },
                      child: Container(
                        padding: EdgeInsets.all(16),
                        margin: EdgeInsets.only(
                          left: 16,
                          right: 16,
                          bottom: 16,
                        ),
                        width: double.infinity,
                        decoration: BoxDecoration(
                          color: AppColors.white,
                          borderRadius: BorderRadius.circular(8),
                        ),
                        child: AspectRatio(
                          aspectRatio: 16 / 9,
                          child:
                              _formData['idcardBackUrl'] != null &&
                                      _formData['idcardBackUrl'].isNotEmpty
                                  ? Image.network(
                                    _formData['idcardBackUrl'],
                                    fit: BoxFit.cover,
                                  )
                                  : Column(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      Icon(
                                        Icons.add_a_photo_outlined,
                                        size: 24,
                                        color: AppColors.textSecondary,
                                      ),
                                      SizedBox(height: 8),
                                      Text('上传国徽面照片'),
                                    ],
                                  ),
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
          Container(
            height: 48,
            padding: EdgeInsets.symmetric(horizontal: 16),
            width: double.infinity,
            child: ElevatedButton(
              onPressed: () {
                submit();
              },
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(
                    Icons.add_circle_outline,
                    color: AppColors.white,
                    size: 24,
                  ),
                  SizedBox(width: 8),
                  Text(
                    '提交审核',
                    style: TextStyle(color: AppColors.white, fontSize: 16),
                  ),
                ],
              ),
            ),
          ),
          SizedBox(height: 16),
        ],
      ),
    );
  }
}
